<template>
  <view class="container">
    <!-- 登录提示条 -->
    <view class="login-tip" v-if="!isLogin">
      <text>登录后可查看更多精彩内容</text>
      <button class="login-btn" @click="goLogin">去登录</button>
    </view>

    <!-- 顶部区域 -->
    <view class="header">
      <view class="search-bar" @click="handleAction('search')">
        <uni-icons type="search" size="18" color="#3a8838"></uni-icons>
        <input type="text" placeholder="搜索照片、相册" placeholder-style="color: #999;" disabled />
      </view>
    </view>
    
    <!-- 相册分类区域 -->
    <view class="section albums-section">
      <view class="section-header">
        <text class="section-title">我的相册</text>
        <text class="more" @click="handleAction('albumMore')">查看更多 ></text>
      </view>
      
      <template v-if="isLogin">
        <view v-if="loading.albums" class="loading-tip">
          <u-loading-icon mode="circle" size="24" color="#3a8838"></u-loading-icon>
          <text>加载中...</text>
        </view>
        <template v-else>
          <template v-if="albums.length">
            <view class="album-categories">
              <view class="category-card" 
                v-for="album in albums" 
                :key="album.albumId" 
                @click="handleAction('albumSelect', album)"
              >
                <view class="category-card-inner">
                  <image 
                    v-if="album.coverUrl" 
                    :src="album.coverUrl"
                    mode="aspectFill" 
                    class="album-cover"
                    @error="handleImageError"
                  />
                  <view v-else class="no-cover">
                    <uni-icons type="image" size="28" color="#fff"></uni-icons>
                  </view>
                </view>
                <text class="category-name">{{album.title}}</text>
                <text class="category-count" v-if="album.photoCount">{{album.photoCount}}张</text>
              </view>
            </view>
          </template>
          <view v-else class="empty-tip">
            <text>暂无相册</text>
          </view>
        </template>
      </template>
      <view v-else class="empty-tip">
        <text>登录后查看相册分类</text>
      </view>
    </view>
    
    <!-- 精选照片区域 -->
    <view class="section featured-section">
      <view class="section-header">
        <text class="section-title">精选照片</text>
        <text class="more" @click="handleAction('featuredMore')">查看更多 ></text>
      </view>
      
      <template v-if="isLogin">
        <view v-if="loading.featured" class="loading-tip">
          <u-loading-icon mode="circle" size="24" color="#3a8838"></u-loading-icon>
          <text>加载中...</text>
        </view>
        <template v-else>
          <template v-if="featuredPhotos.length">
            <swiper class="featured-swiper" 
                  indicator-dots 
                  indicator-active-color="#3a8838" 
                  indicator-color="rgba(255, 255, 255, 0.6)"
                  autoplay 
                  interval="5000"
                  circular>
              <swiper-item v-for="(photo, index) in featuredPhotos" :key="index">
                <view class="featured-item" @click="handleAction('photoSelect', photo, index)">
                  <image :src="photo.photoUrl || '/static/src.png'" mode="aspectFill"></image>
                  <view class="featured-info">
                    <text class="featured-title">{{photo.title || '精选照片'}}</text>
                    <text class="featured-date">{{formatDate(photo.createTime)}}</text>
                  </view>
                </view>
              </swiper-item>
            </swiper>
          </template>
          <view v-else class="empty-tip">
            <text>暂无精选照片</text>
          </view>
        </template>
      </template>
      <view v-else class="empty-tip">
        <text>登录后查看精选照片</text>
      </view>
    </view>
    
    <!-- 最近上传区域 -->
    <view class="section recent-section">
      <view class="section-header">
        <text class="section-title">最近上传</text>
        <text class="more" @click="handleAction('recentMore')">查看更多 ></text>
      </view>
      
      <template v-if="isLogin">
        <view v-if="loading.recent" class="loading-tip">
          <u-loading-icon mode="circle" size="24" color="#3a8838"></u-loading-icon>
          <text>加载中...</text>
        </view>
        <template v-else>
          <template v-if="recentPhotos.length">
            <view class="recent-grid">
              <view class="grid-item" 
                v-for="(photo, index) in recentPhotos" 
                :key="photo.photoId" 
                @click="handleAction('photoSelect', photo, index)"
              >
                <image 
                  :src="photo.photoUrl || '/static/default-photo.png'" 
                  mode="aspectFill"
                  @error="handleImageError"
                ></image>
                <view class="photo-info">
                  <text class="photo-date">{{formatDate(photo.uploadTime)}}</text>
                </view>
              </view>
            </view>
          </template>
          <view v-else class="empty-tip">
            <text>暂无最近上传</text>
          </view>
        </template>
      </template>
      <view v-else class="empty-tip">
        <text>登录后查看最近上传</text>
      </view>
    </view>
    
    <tab-bar :tabIndex="0"></tab-bar>
  </view>
</template>

<script>
import AlbumHeader from '@/components/album/AlbumHeader.vue'
import TabBar from '@/components/tab-bar/tab-bar.vue'
import { getMyAlbums } from '@/api/album'
import { getMyFavoritePhotos, getRecentPhotos } from '@/api/photo'
import { formatDate } from '@/utils/date'
import { useDebounce } from '@/utils/debounce'
import Vue from 'vue'
import { getImageBlob } from '@/utils/image.js'
import config from '@/config/index.js'

export default {
  components: {
    AlbumHeader,
    TabBar
  },
  data() {
    return {
      isLogin: false,
      albums: [],
      featuredPhotos: [],
      recentPhotos: [],
      loading: {
        albums: false,
        featured: false,
        recent: false
      },
      gradients: [
        { start: '#4CAF50', end: '#2E7D32' },
        { start: '#2196F3', end: '#1565C0' },
        { start: '#FF9800', end: '#E65100' },
        { start: '#9C27B0', end: '#6A1B9A' }
      ],
      icons: ['images', 'star', 'map', 'home']
    }
  },
  created() {
    this.$bus.$on('auth:login-success', this.handleLoginSuccess)
  },
  beforeDestroy() {
    this.$bus.$off('auth:login-success', this.handleLoginSuccess)
  },
  async onLoad() {
    // 检查登录状态
    this.isLogin = !!uni.getStorageSync('token');
    
    if (this.isLogin) {
      // 并行加载数据
      await Promise.all([
        this.loadAlbums(),
        this.loadFeatured()
      ]);
    }
  },
  onShow() {
    console.log('首页显示')
    this.checkLoginStatus(true)
  },
  methods: {
    setupUI() {
      // Implementation of setupUI method
    },
    async checkLoginStatusOnly() {
      // 先检查本地token
      const token = uni.getStorageSync('token')
      console.log('只检查登录状态: 存储token:', !!token)
      
      if (token) {
        if (!this.$store.state.isLogin) {
          try {
            const result = await this.$store.dispatch('initAuthState')
            this.isLogin = this.$store.state.isLogin
            if (!this.isLogin) {
              this.handleTokenExpired()
            }
            return this.isLogin
          } catch (error) {
            console.error('验证token时出错:', error)
            this.handleTokenExpired()
            return false
          }
        } else {
          this.isLogin = true
          return true
        }
      } else {
        this.isLogin = false
        return false
      }
    },
    async checkLoginStatus(loadDataAfterCheck = false) {
      // 先检查本地token
      const token = uni.getStorageSync('token')
      console.log('检查登录状态: 存储token:', !!token, 'store登录状态:', this.$store.state.isLogin)
      
      if (token) {
        if (!this.$store.state.isLogin) {
          console.log('发现token但未登录，尝试初始化认证状态')
          try {
            const result = await this.$store.dispatch('initAuthState')
            console.log('认证状态初始化完成, isLogin:', this.$store.state.isLogin, '结果:', result)
            
            this.isLogin = this.$store.state.isLogin
            if (!this.isLogin) {
              this.handleTokenExpired()
              return false
            } else if (loadDataAfterCheck) {
              // 已确认登录状态，加载数据
              console.log('token有效，加载数据')
              this.loadData()
            }
            return this.isLogin
          } catch (error) {
            console.error('验证token时出错:', error)
            this.handleTokenExpired()
            return false
          }
        } else {
          // 已登录状态，直接更新并加载数据
          this.isLogin = true
          if (loadDataAfterCheck) {
            console.log('已确认登录状态，加载数据')
            this.loadData()
          }
          return true
        }
      } else {
        // 无token，未登录状态
        this.isLogin = false
        return false
      }
    },
    // 处理token过期情况的方法
    handleTokenExpired() {
      console.log('token验证失败，需要重新登录')
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      })
      // 清除可能过期的token
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      this.isLogin = false
    },
    
    async loadData() {
      // 如果未登录或数据已加载，不再重复加载
      if (!this.isLogin) {
        console.log('未登录，不加载数据')
        return
      }
      
      console.log('开始加载所有数据');
      // 同时加载所有数据区块
      this.loadAlbums();
      this.loadFeatured();
      this.loadRecent();
    },
    
    // 加载相册数据
    async loadAlbums() {
      if (!this.isLogin) return;
      
      this.loading.albums = true;
      try {
        const result = await getMyAlbums();
        const albums = result.data?.records || [];
        
        // 并行处理所有相册封面
        const coverPromises = albums.map(async album => {
          if (album.coverPhoto) {
            try {
              album.coverUrl = await getImageBlob(album.coverPhoto);
            } catch (err) {
              console.error('加载封面失败:', err);
              album.coverUrl = '';
            }
          }
          return album;
        });
        
        // 等待所有封面加载完成
        await Promise.all(coverPromises);
        
        this.albums = albums;
      } catch (error) {
        console.error('加载相册失败:', error);
        uni.showToast({
          title: '加载相册失败',
          icon: 'none'
        });
      } finally {
        this.loading.albums = false;
      }
    },
    
    // 加载精选照片
    async loadFeatured() {
      if (!this.isLogin) return;
      
      // 设置加载状态
      this.loading.featured = true;
      
      try {
        console.log('加载精选照片...');
        const featuredRes = await getMyFavoritePhotos();
        this.featuredPhotos = featuredRes.data || [];
        console.log('精选照片加载完成:', this.featuredPhotos.length);
      } catch (error) {
        console.error('加载精选照片失败:', error);
      } finally {
        this.loading.featured = false;
      }
    },
    
    // 加载最近照片
    async loadRecent() {
      if (!this.isLogin) return;
      
      // 设置加载状态
      this.loading.recent = true;
      
      try {
        console.log('加载最近照片...');
        const recentRes = await getRecentPhotos();
        // 从分页数据中获取照片列表
        const photos = recentRes.data?.records || [];
        
        // 处理每张照片的URL
        for (const photo of photos) {
          try {
            photo.photoUrl = await getImageBlob(photo.photoPath);
          } catch (err) {
            console.error('加载照片失败:', err);
            photo.photoUrl = '';
          }
        }
        
        this.recentPhotos = photos;
        console.log('最近照片加载完成:', this.recentPhotos.length);
      } catch (error) {
        console.error('加载最近照片失败:', error);
      } finally {
        this.loading.recent = false;
      }
    },
    formatDate(dateString) {
      if (!dateString) return ''
      
      // 处理日期格式兼容性问题
      // 将 "yyyy-MM-dd HH:mm:ss" 转换为 "yyyy/MM/dd HH:mm:ss" 或 "yyyy-MM-ddTHH:mm:ss"
      if (dateString.includes(' ')) {
        // 方法1：使用/替换-，iOS支持 yyyy/MM/dd HH:mm:ss 格式
        const formattedDate = dateString.replace(/-/g, '/');
        return formatDate(new Date(formattedDate), 'yyyy-MM-dd');
        
        // 方法2：使用T替换空格，iOS支持 yyyy-MM-ddTHH:mm:ss 格式
        // const formattedDate = dateString.replace(' ', 'T');
        // return formatDate(new Date(formattedDate), 'yyyy-MM-dd');
      }
      
      return formatDate(new Date(dateString), 'yyyy-MM-dd')
    },
    goLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    },
    handleAction(action, data) {
      if (!this.isLogin) {
        uni.navigateTo({
          url: '/pages/login/login'
        })
        return
      }
      
      switch (action) {
        case 'search':
          console.log('搜索功能')
          break
        case 'albumMore':
          uni.navigateTo({
            url: '/pages/my/albums'
          })
          break
        case 'albumSelect':
          if (data && data.albumId) {
            uni.navigateTo({
              url: `/pages/album/detail?id=${data.albumId}`
            })
          }
          break
        case 'featuredMore':
          console.log('查看更多精选照片')
          break
        case 'recentMore':
          console.log('查看更多最近照片')
          break
        case 'photoSelect':
          const [photo, index] = data
          console.log('选择照片', photo, index)
          break
      }
    },
    handleAddPhoto() {
      console.log('添加照片');
    },
    handleLoginSuccess(data) {
      console.log('接收到登录成功事件，重新加载数据')
      
      // 根据传入的参数决定刷新方式
      const isTokenRefresh = data && data.refreshToken;
      
      if (isTokenRefresh) {
        console.log('因token刷新而重新加载，执行完整刷新');
        
        // 先重置loading状态，以防页面卡在loading状态
        this.loading = {
          albums: false,
          featured: false, 
          recent: false
        };
        
        // 直接触发数据加载
        console.log('直接触发所有数据加载');
        // 设置为已登录状态
        this.isLogin = true;
        // 立即加载所有数据
        this.loadAlbums();
        this.loadFeatured();
        this.loadRecent();
      } else {
        // 普通的登录成功，只需检查登录状态
        this.checkLoginStatus();
      }
      
      uni.showToast({
        title: isTokenRefresh ? '已自动重新登录' : '登录成功',
        icon: 'success',
        duration: 1500
      })
    },
    // 执行完整页面刷新
    fullPageRefresh() {
      console.log('执行完整页面刷新');
      // 清除当前页面数据
      this.albums = [];
      this.featuredPhotos = [];
      this.recentPhotos = [];
      
      // 重置加载状态
      this.loading = {
        albums: true,
        featured: true,
        recent: true
      };
      
      // 直接调用加载数据方法，绕过登录检查（因为已经登录成功）
      console.log('执行数据加载...');
      
      // 确认已登录状态
      this.isLogin = true;
      console.log('设置登录状态为true，准备加载数据');
      
      // 强制延迟一点点时间后再加载，确保状态已更新
      setTimeout(() => {
        this.loadAlbums();
        this.loadFeatured();
        this.loadRecent();
        console.log('已触发所有数据加载请求');
      }, 100);
    },
    // 处理图片加载错误
    handleImageError(e) {
      console.error('图片加载失败:', e);
      // 可以设置一个默认图片
      e.target.src = '/static/default-cover.png';
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.header {
  padding: 10rpx 0 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #3a8838;
  margin-bottom: 15rpx;
  display: block;
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  padding: 16rpx 25rpx;
  border-radius: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.search-bar input {
  margin-left: 15rpx;
  font-size: 28rpx;
  width: 100%;
  color: #333;
}

.section {
  background-color: #ffffff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 15rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 30rpx;
  background-color: #3a8838;
  border-radius: 4rpx;
}

.more {
  font-size: 24rpx;
  color: #3a8838;
}

.album-categories {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
  padding: 10rpx;
}

.category-card {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.category-card-inner {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  overflow: hidden;
  margin-bottom: 12rpx;
}

.album-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-cover {
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom right, #4CAF50, #2E7D32);
  display: flex;
  align-items: center;
  justify-content: center;
}

.category-name {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 4rpx;
}

.category-count {
  font-size: 22rpx;
  color: #999;
}

.featured-swiper {
  height: 400rpx;
  border-radius: 15rpx;
  overflow: hidden;
}

.featured-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.featured-item image {
  width: 100%;
  height: 100%;
  border-radius: 15rpx;
}

.featured-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx 20rpx 20rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), rgba(0,0,0,0));
  border-bottom-left-radius: 15rpx;
  border-bottom-right-radius: 15rpx;
}

.featured-title {
  font-size: 32rpx;
  color: #fff;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
}

.featured-date {
  font-size: 24rpx;
  color: rgba(255,255,255,0.8);
}

.recent-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -8rpx;
}

.grid-item {
  width: calc(33.33% - 16rpx);
  height: 220rpx;
  margin: 8rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.grid-item image {
  width: 100%;
  height: 100%;
  transition: transform 0.3s;
}

.grid-item:active image {
  transform: scale(1.05);
}

.photo-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8rpx 12rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), rgba(0,0,0,0));
}

.photo-date {
  font-size: 22rpx;
  color: #fff;
}

.float-btn {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #4CAF50, #2E7D32);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
  z-index: 100;
  transition: transform 0.2s, box-shadow 0.2s;
}

.float-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
}

.login-tip {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 30rpx;
  background-color: rgba(58, 136, 56, 0.1);
  border-bottom: 1rpx solid rgba(58, 136, 56, 0.2);
}

.login-tip text {
  font-size: 26rpx;
  color: #3a8838;
}

.login-tip .login-btn {
  background: #3a8838;
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 30rpx;
  border-radius: 30rpx;
  margin: 0;
  line-height: 1.5;
}

.login-btn::after {
  border: none;
}

.empty-tip {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
}

.loading-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  color: #666;
  font-size: 28rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
}

.loading-tip text {
  margin-left: 16rpx;
}
</style>